package petrochina.company.electric.ui.fragment;

import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.layout.WrapRecyclerView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import petrochina.company.electric.R;
import petrochina.company.electric.aop.SingleClick;
import petrochina.company.electric.app.TitleBarFragment;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.api.TaskFillApi;
import petrochina.company.electric.http.api.TaskFillSubmitApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.model.TaskFillAreaData;
import petrochina.company.electric.model.TaskFillResult;
import petrochina.company.electric.model.TaskFillResultData;
import petrochina.company.electric.model.TaskFillStationData;
import petrochina.company.electric.model.TaskFillUserData;
import petrochina.company.electric.ui.activity.HomeActivity;
import petrochina.company.electric.ui.adapter.FillSearchAdapter;
import petrochina.company.electric.ui.dialog.FillSelectDialog;

/**
 * 填报
 */
public final class FillFragment extends TitleBarFragment<HomeActivity> implements BaseAdapter.OnItemClickListener {

    private AttachPopupView rightTitlePop;

    private AppCompatEditText mSearch;


    //作业区选择
    private SettingBar mWorkplaceSb;

    //站点选择
    private SettingBar mStationSb;

    //用户名
    private SettingBar mUserNameSb;

    private AppCompatEditText mBatteryEt;

    private LinearLayout mContentView;
    private WrapRecyclerView mRecyclerView;

    private AppCompatButton btnSave, btnAllSubmit;

    private LinearLayout llLoadData;

    private TextView tvAverageElectricity;

    private FillSearchAdapter mAdapter;

    private LoginApi.Bean loginData;
    private MMKV mmkv;
    private Gson gson;

    protected String search; // 当前关键字
    private List<TaskFillAreaData> mData;
    private TaskFillAreaData currentArea;
    private TaskFillStationData currentStation;
    private TaskFillUserData currentUser;
    private TaskFillResult mResult;

    public static FillFragment newInstance() {
        return new FillFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fill_fragment;
    }

    @Override
    protected void initView() {
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();

        mContentView = findViewById(R.id.ll_content);
        llLoadData = findViewById(R.id.ll_load_data);
        mSearch = findViewById(R.id.et_fill_search);
        mWorkplaceSb = findViewById(R.id.sb_work_place);
        mStationSb = findViewById(R.id.sb_station);
        mUserNameSb = findViewById(R.id.sb_user_name);
        mBatteryEt = findViewById(R.id.et_battery);
        btnSave = findViewById(R.id.btn_save);
        btnAllSubmit = findViewById(R.id.btn_all_submit);
        tvAverageElectricity = findViewById(R.id.tv_average_electricity);
        setOnClickListener(R.id.ll_load_data, R.id.sb_work_place, R.id.sb_station, R.id.sb_user_name, R.id.btn_search, R.id.btn_save, R.id.btn_all_submit);


        mRecyclerView = findViewById(R.id.rv_fill_list);
        mAdapter = new FillSearchAdapter(getAttachActivity());
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);

        TextView headerView = mRecyclerView.addHeaderView(R.layout.fill_item_cancel);
        headerView.setText("取消搜索");
        headerView.setOnClickListener(v -> showContentView(0));
    }

    @Override
    protected void initData() {
        String loginJson = mmkv.getString("loginData", null);
        if (!TextUtils.isEmpty(loginJson)) {
            loginData = gson.fromJson(loginJson, LoginApi.Bean.class);
        }
        if (loginData == null) {
            finish();
        }
        String historyFillDataStr = mmkv.getString("historyFillData", null);
        if (!TextUtils.isEmpty(historyFillDataStr)) {
            mData = gson.fromJson(historyFillDataStr, new TypeToken<List<TaskFillAreaData>>() {
            }.getType());
        }
        if (mData == null) {
            ToastUtils.show("请下载历史填报数据!");
        }
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_load_data:
                getLoadData();
                break;
            case R.id.sb_work_place:
                chooseUser(0);
                break;
            case R.id.sb_station:
                chooseUser(1);
                break;
            case R.id.sb_user_name:
                chooseUser(2);
                break;
//            case R.id.et_battery:
//                break;
            case R.id.btn_search:
                //显示搜索
                showContentView(1);
                break;
            case R.id.btn_save:
                localSaveData();
                break;
            case R.id.btn_all_submit:
                submitData();
                break;
        }
    }

    private void submitData() {
        ToastUtils.show(mData.toString());
        if (mData == null || mData.size() == 0) {
            ToastUtils.show("请下载历史填报数据!");
        } else {
            String resultJson = mmkv.getString("fillResultData", null);
            if (!TextUtils.isEmpty(resultJson)) {
                mResult = gson.fromJson(resultJson, TaskFillResult.class);
                if (mResult != null && mResult.getData() != null && mResult.getData().size() > 0) {
                    for (TaskFillAreaData areaData : mData) {
                        for (TaskFillStationData stationData : areaData.getStations()) {
                            for (TaskFillUserData userData : stationData.getUsers()) {
                                TaskFillResultData resultData = new TaskFillResultData(0, 0, userData.getId(), null);
                                if (!mResult.getData().contains(resultData)) {
                                    // 比对保存数据中所有用户数据是否存在，若不存在则提示
                                    ToastUtils.show("作业区" + areaData.getAreaName() + "尚未完成\n请输入完整数据后统一提交");
                                    return;
                                }
                            }
                        }
                    }
                    // 数据统一比对后提交
                    String resultString = gson.toJson(mResult);
                    ToastUtils.show(resultString);
                    submitResult(resultString);
                }
            } else {
                ToastUtils.show("作业区" + mData.get(0).getAreaName() + "尚未完成\n请输入完整数据后统一提交");
            }
        }
    }

    private void localSaveData() {
        if (currentArea != null && currentStation != null && currentUser != null && mBatteryEt.getText() != null && !TextUtils.isEmpty(mBatteryEt.getText().toString().trim())) {
            TaskFillResultData mResultData = new TaskFillResultData(currentArea.getId(), currentStation.getId(), currentUser.getId(), mBatteryEt.getText().toString().trim());
            String resultJson = mmkv.getString("fillResultData", null);
            if (!TextUtils.isEmpty(resultJson)) {
                mResult = gson.fromJson(resultJson, TaskFillResult.class);
            } else {
                mResult = new TaskFillResult(loginData.getId(), new ArrayList<>());
            }
            if (mResult.getData().size() > 0) {
                if (mResult.getData().contains(mResultData)) {
                    mResult.getData().get(mResult.getData().indexOf(mResultData)).setDegrees(mResultData.getDegrees());
                } else {
                    mResult.getData().add(mResultData);
                }
            } else {
                mResult.getData().add(mResultData);
            }
            mmkv.putString("fillResultData", gson.toJson(mResult));
            int areaIndex = mData.indexOf(currentArea);
            List<TaskFillStationData> stationList = mData.get(areaIndex).getStations();
            int stationIndex = stationList.indexOf(currentStation);
            List<TaskFillUserData> userList = stationList.get(stationIndex).getUsers();
            int userIndex = userList.indexOf(currentUser);
            mData.get(areaIndex).getStations().get(stationIndex).getUsers().get(userIndex).setWrite(true);
            for (int i = 0; i < mData.get(areaIndex).getStations().get(stationIndex).getUsers().size(); i++) {
                TaskFillUserData userData = mData.get(areaIndex).getStations().get(stationIndex).getUsers().get(i);
                if (!userData.isWrite()) {
                    break;
                }
                if (i == mData.get(areaIndex).getStations().get(stationIndex).getUsers().size() - 1) {
                    // 若最后一条仍填写完
                    mData.get(areaIndex).getStations().get(stationIndex).setWrite(true);

                    for (int j = 0; j < mData.get(areaIndex).getStations().size(); j++) {
                        TaskFillStationData stationData = mData.get(areaIndex).getStations().get(j);
                        if (!stationData.isWrite()) {
                            break;
                        }
                        if (j == mData.get(areaIndex).getStations().size() - 1) {
                            // 若最后一条仍填写完
                            mData.get(areaIndex).setWrite(true);
                        }
                    }
                }
            }
            // 本地保存后更新本地历史数据
            mmkv.putString("historyFillData", gson.toJson(mData));
            mAdapter.notifyDataSetChanged();
            ToastUtils.show("保存成功！");
            resetEditView();

        } else {
            ToastUtils.show("请补全信息");
        }
    }

    private void resetEditView() {
        currentArea = null;
        currentStation = null;
        currentUser = null;
        mWorkplaceSb.setRightText(null);
        mStationSb.setRightText(null);
        mUserNameSb.setRightText(null);
        mBatteryEt.setText(null);
        tvAverageElectricity.setText(0 + "");
    }

    private void submitResult(String json) {
        EasyHttp.post(this)
                .api(new TaskFillSubmitApi())
                .json(json)
                .request(new HttpCallback<HttpData<TaskFillAreaData>>(this) {

                    @Override
                    public void onSucceed(HttpData<TaskFillAreaData> result) {
                        mmkv.remove("fillResultData");
                        ToastUtils.show("提交成功");
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        ToastUtils.show("提交失败");
                    }
                });
    }

    private void getLoadData() {
        EasyHttp.get(this)
                .api(new TaskFillApi()
                        .setUserId(loginData.getId()))
                .request(new HttpCallback<HttpData<List<TaskFillAreaData>>>(this) {

                    @Override
                    public void onSucceed(HttpData<List<TaskFillAreaData>> result) {
                        // 数据集不为空
                        if (result != null && result.getData() != null && result.getData().size() > 0) {
                            // 本地保存结果集不为空
                            String resultJson = mmkv.getString("fillResultData", null);
                            if (!TextUtils.isEmpty(resultJson)) {
                                mResult = gson.fromJson(resultJson, TaskFillResult.class);
                            }
                            if (mResult != null && mResult.getData() != null && mResult.getData().size() != 0) {
                                // 更新所有用户状态
                                for (TaskFillAreaData areaData : result.getData()) {
                                    for (TaskFillStationData stationData : areaData.getStations()) {
                                        for (TaskFillUserData userData : stationData.getUsers()) {
                                            TaskFillResultData tempUser = new TaskFillResultData(0, 0, userData.getId(), null);
                                            if (mResult.getData().contains(tempUser)) {
                                                userData.setWrite(true);
                                            }
                                        }
                                    }
                                }
                                // 更新所有站状态
                                boolean isStationWrite = false;
                                for (TaskFillAreaData areaData : result.getData()) {
                                    for (TaskFillStationData stationData : areaData.getStations()) {
                                        isStationWrite = true;
                                        for (TaskFillUserData userData : stationData.getUsers()) {
                                            if (isStationWrite || !userData.isWrite()) {
                                                isStationWrite = false;
                                            }
                                        }
                                        if (isStationWrite) {
                                            stationData.setWrite(true);
                                        }
                                    }
                                }

                                // 更新所有区状态
                                boolean isAreaWrite = false;
                                for (TaskFillAreaData areaData : result.getData()) {
                                    isAreaWrite = true;
                                    for (TaskFillStationData stationData : areaData.getStations()) {
                                        if (isAreaWrite || !stationData.isWrite()) {
                                            isAreaWrite = false;
                                        }
                                    }
                                    if (isStationWrite) {
                                        areaData.setWrite(true);
                                    }
                                }
                            }
                            mData = result.getData();
                            mmkv.putString("historyFillData", gson.toJson(mData));
                            ToastUtils.show("历史数据下载成功");
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        ToastUtils.show("历史数据下载失败");
                    }
                });
    }

    private void showContentView(int type) {
        if (type == 0) {
            mContentView.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            mContentView.setVisibility(View.INVISIBLE);
//            mAdapter.setData(analogData());
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void chooseUser(int type) {
        List<Object> selectList = new ArrayList<>();
        if (mData != null && mData.size() > 0) {
            String title;
            if (type == 0) {
                title = "请选择作业区";
//                for (TaskFillAreaData bean : mData) {
//                    strList.add(bean.getAreaName());
//                }
                selectList.addAll(mData);
            } else if (type == 1) {
                title = "请选择站";
                if (currentArea == null) {
                    ToastUtils.show("您还未选择作业区");
                    return;
                }
//                for (TaskFillStationData bean : currentArea.getStations()) {
//                    strList.add(bean.getStationName());
//                }
                selectList.addAll(currentArea.getStations());
            } else {
                title = "请选择用户";
                if (currentArea == null) {
                    ToastUtils.show("您还未选择作业区");
                    return;
                } else if (currentStation == null) {
                    ToastUtils.show("您还未选择站");
                    return;
                }
//                for (TaskFillUserData bean : currentStation.getUsers()) {
//                    strList.add(bean.getUserName());
//                }
                selectList.addAll(currentStation.getUsers());
            }

            // 底部选择框
            new FillSelectDialog.Builder(getAttachActivity())
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setCancel(null)
                    .setList(selectList)
                    .setListener(new FillSelectDialog.OnListener<Object>() {

                        @Override
                        public void onSelected(BaseDialog dialog, int position, Object data) {
//                            toast("位置：" + position + "，文本：" + string);
                            if (type == 0) {
                                currentArea = mData.get(position);
                                mWorkplaceSb.setRightText(currentArea.getAreaName());
                            } else if (type == 1) {
                                currentStation = currentArea.getStations().get(position);
                                mStationSb.setRightText(currentStation.getStationName());
                            } else {
                                currentUser = currentStation.getUsers().get(position);
                                mUserNameSb.setRightText(currentUser.getUserName());
                                tvAverageElectricity.setText(currentUser.getAverageDegree() + "");
                            }
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
//                            toast("取消了");
                        }
                    })
                    .show();
        } else {
            ToastUtils.show("请下载历史填报数据!");
        }
//        // 选择地区对话框
//        new AddressDialog.Builder(getContext())
//                .setTitle(title)
//                // 设置默认省份
//                //.setProvince("广东省")
//                // 设置默认城市（必须要先设置默认省份）
//                //.setCity("广州市")
//                // 不选择县级区域
//                //.setIgnoreArea()
//                .setListener(new AddressDialog.OnListener() {
//
//                    @Override
//                    public void onSelected(BaseDialog dialog, String province, String city, String area) {
//                        mWorkplaceSb.setRightText(province);
//                        mStationSb.setRightText(city);
//                        mUserNameSb.setRightText(area);
//                        toast(province + city + area);
//                    }
//
//                    @Override
//                    public void onCancel(BaseDialog dialog) {
//                        toast("取消了");
//                    }
//                })
//                .show();
    }


    @Override
    public void onRightClick(View view) {
        rightTitlePop = new XPopup.Builder(getContext())
                .borderRadius(10)
                .hasShadowBg(false)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .offsetX(30)
                .shadowBgColor(R.drawable.shape_bar_pop_bg)
                .atView(view)
                .asAttachList(new String[]{"全部", "已输入", "未输入"},
                        new int[]{},
                        (position, text) -> {
                            getTitleBar().setRightTitle(text);
                            int type = position;
                            toast(text);
                            // 刷新
                        });
        rightTitlePop.show();
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        showContentView(0);
    }
}